package com.zrwl.poscloud.xo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zrwl.poscloud.base.entity.CallProductConfig;
import com.zrwl.poscloud.base.entity.Sequence;
import com.zrwl.poscloud.base.entity.UserServiceOrder;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrwl.poscloud.base.entity.UserServiceOrderDetail;
import com.zrwl.poscloud.base.enums.EBusiType;
import com.zrwl.poscloud.base.enums.EBusinessType;
import com.zrwl.poscloud.base.enums.EStatus;
import com.zrwl.poscloud.base.superI.SuperServiceImpl;
import com.zrwl.poscloud.commons.holder.RequestHolder;
import com.zrwl.poscloud.commons.utils.DateUtils;
import com.zrwl.poscloud.commons.utils.ResultUtil;
import com.zrwl.poscloud.commons.utils.StringUtils;
import com.zrwl.poscloud.xo.global.MessageConf;
import com.zrwl.poscloud.xo.global.SQLConf;
import com.zrwl.poscloud.xo.global.SysConf;
import com.zrwl.poscloud.xo.mapper.CallProductConfigMapper;
import com.zrwl.poscloud.xo.mapper.UserServiceConfigDetailMapper;
import com.zrwl.poscloud.xo.mapper.UserServiceOrderUseMapper;
import com.zrwl.poscloud.xo.service.*;
import com.zrwl.poscloud.xo.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zrwl.poscloud.xo.mapper.UserServiceOrderMapper;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 服务采购 服务实现类
 *
 * @author 刘思童 AutoGenerate
 * @date 2023-02-28
 */
@Service
public class UserServiceOrderServiceImpl extends SuperServiceImpl<UserServiceOrderMapper, UserServiceOrder> implements UserServiceOrderService {

    @Autowired
    private UserServiceOrderService userServiceOrderService;
    @Resource
    private UserServiceOrderMapper userServiceOrderMapper;
    @Autowired
    private AdminService adminService;
    @Autowired
    private SequenceService sequenceService;
    @Autowired
    private UserServiceOrderDetailService userServiceOrderDetailService;
    @Autowired
    private CallProductOrderService callProductOrderService;
    @Autowired
    private CallProductConfigService callProductConfigService;

    @Override
    public IPage<UserServiceOrderVO> getPageList(UserServiceOrderVO userServiceOrderVO) {
        Page<UserServiceOrderVO> page = new Page<>();
        page.setCurrent(userServiceOrderVO.getCurrentPage());
        page.setSize(userServiceOrderVO.getPageSize());
        IPage<UserServiceOrderVO> pageList = userServiceOrderMapper.getPageList(page, userServiceOrderVO);
        List<UserServiceOrderVO> list = pageList.getRecords();
        pageList.setRecords(list);
        return pageList;
    }

    @Override
    public List<UserServiceOrder> getAllList(UserServiceOrderVO userServiceOrderVO) {
        QueryWrapper<UserServiceOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne(SQLConf.STATUS, EStatus.DISABLED);
        queryWrapper.orderByAsc(SQLConf.CREATE_TIME);
        List<UserServiceOrder> list = userServiceOrderService.list(queryWrapper);
        return list;
    }

    @Override
    public String add(UserServiceOrderVO userServiceOrderVO) {
        //套餐内容
        List<BusinessProductDetailVO> businessCustomer = userServiceOrderMapper.getPackageContent(userServiceOrderVO.getConfigUid());
        if (businessCustomer != null && businessCustomer.size() > 0) {
            String dateFormat = JSON.toJSONStringWithDateFormat(businessCustomer, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat);
            userServiceOrderVO.setProductDetailJson(dateFormat);
        }
        UserServiceOrder entity = new UserServiceOrder();
        BeanUtils.copyProperties(userServiceOrderVO, entity, SysConf.STATUS);
        entity.insert();
        userServiceOrderVO.setUid(entity.getUid());
        UserServiceOrderDetailVO userServiceOrderDetailVO = null;
        if (businessCustomer != null) {
            List<UserServiceOrderDetailVO> list = userServiceOrderDetailService.getOrderDetailByEmployeeUid(userServiceOrderVO.getEmployeeUid());
            Map<String,BusinessProductDetailVO> productDetailMap = new HashMap<>();
            for (BusinessProductDetailVO businessProductDetailVO : businessCustomer) {
                productDetailMap.put(businessProductDetailVO.getCellUid(),businessProductDetailVO);
            }
            if (list.size() > 0) {
                for (UserServiceOrderDetailVO serviceOrderDetailVO : list) {
                    BusinessProductDetailVO businessProductDetailVO = productDetailMap.get(serviceOrderDetailVO.getCellUid());
                    if(businessProductDetailVO != null){
                        userServiceOrderDetailVO = new UserServiceOrderDetailVO();
                        userServiceOrderDetailVO.setOrderUid(entity.getUid());
                        userServiceOrderDetailVO.setCellUid(businessProductDetailVO.getCellUid());
                        userServiceOrderDetailVO.setUseBeginTime(serviceOrderDetailVO.getUseEndTime());
                        userServiceOrderDetailVO.setCount(Integer.parseInt(userServiceOrderVO.getCount()) * (businessProductDetailVO.getServiceDay()*businessProductDetailVO.getCount()));
                        userServiceOrderDetailVO.setUseEndTime(DateUtils.addDays(serviceOrderDetailVO.getUseEndTime(),userServiceOrderDetailVO.getCount()));
                        userServiceOrderDetailVO.setStatus(1);
                        userServiceOrderDetailVO.setUsedCount(0);
                        CallProductConfig productConfig = callProductConfigService.getById(businessProductDetailVO.getCallUid());
                        if(productConfig != null){
                            CallProductOrderVO callProductOrderVO = new CallProductOrderVO();
                            callProductOrderVO.setProductUid(productConfig.getUid());
                            callProductOrderVO.setAmt(productConfig.getBillingAmt());
                            callProductOrderVO.setBillingType(productConfig.getBillingWay());
                            callProductOrderVO.setCode(productConfig.getCode());
                            callProductOrderVO.setCount(1);
                            callProductOrderVO.setBeginTime(serviceOrderDetailVO.getUseEndTime());
                            callProductOrderVO.setEndTime(DateUtils.addDays(serviceOrderDetailVO.getUseEndTime(),productConfig.getValidDay()));
                            callProductOrderService.add(callProductOrderVO);
                            userServiceOrderDetailVO.setCallProductOrderUid(callProductOrderVO.getUid());
                        }
                        userServiceOrderDetailService.add(userServiceOrderDetailVO);
                        productDetailMap.put(serviceOrderDetailVO.getCellUid(),null);
                    }
                }
            }
            for (BusinessProductDetailVO businessProductDetailVO : businessCustomer) {
                BusinessProductDetailVO productDetailVO = productDetailMap.get(businessProductDetailVO.getCellUid());
                if(productDetailVO != null){
                    userServiceOrderDetailVO = new UserServiceOrderDetailVO();
                    userServiceOrderDetailVO.setOrderUid(entity.getUid());
                    userServiceOrderDetailVO.setCellUid(businessProductDetailVO.getCellUid());
                    userServiceOrderDetailVO.setCount(Integer.parseInt(userServiceOrderVO.getCount()) * businessProductDetailVO.getServiceDay());
                    userServiceOrderDetailVO.setUseBeginTime(new Date());
                    userServiceOrderDetailVO.setUseEndTime(DateUtils.addDays(new Date(),userServiceOrderDetailVO.getCount()));
                    userServiceOrderDetailVO.setStatus(1);
                    userServiceOrderDetailVO.setUsedCount(0);
                    CallProductConfig productConfig = callProductConfigService.getById(businessProductDetailVO.getCallUid());
                    if(productConfig != null){
                        String dateFormat = JSON.toJSONStringWithDateFormat(productConfig, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat);
                        CallProductOrderVO callProductOrderVO = new CallProductOrderVO();
                        callProductOrderVO.setProductUid(productConfig.getUid());
                        callProductOrderVO.setAmt(productConfig.getBillingAmt());
                        callProductOrderVO.setCode(productConfig.getCode());
                        callProductOrderVO.setProductConfigJson(dateFormat);
                        callProductOrderVO.setBillingType(productConfig.getBillingWay());
                        callProductOrderVO.setCount(1);
                        callProductOrderVO.setBeginTime(new Date());
                        callProductOrderVO.setEndTime(DateUtils.addDays(new Date(),productConfig.getValidDay()));
                        callProductOrderService.add(callProductOrderVO);
                        userServiceOrderDetailVO.setCallProductOrderUid(callProductOrderVO.getUid());
                    }
                    userServiceOrderDetailService.add(userServiceOrderDetailVO);
                }
            }
        }
        return ResultUtil.successWithMessage(MessageConf.INSERT_SUCCESS);
    }

    @Override
    public String edit(UserServiceOrderVO userServiceOrderVO) {
        UserServiceOrder entity = userServiceOrderService.getById(userServiceOrderVO.getUid());
        BeanUtils.copyProperties(userServiceOrderVO, entity);
        entity.updateById();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public String delete(UserServiceOrderVO userServiceOrderVO) {
        UserServiceOrder entity = userServiceOrderService.getById(userServiceOrderVO.getUid());
        entity.setStatus(EStatus.DISABLED);
        entity.updateById();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public String getAutoOrderCode() {
        HttpServletRequest request = RequestHolder.getRequest();
        String ownerUid = null;
        Integer ownerType = null;
        if (request.getAttribute(SysConf.OWNER_UID) != null) {
            ownerUid = request.getAttribute(SysConf.OWNER_UID).toString();
            ownerType = (Integer) request.getAttribute(SysConf.OWNER_TYPE);
        }
        if (ownerType == null || ownerUid == null) {
            AdminVO adminVO = adminService.getMe();
            ownerType = adminVO.getOwnerType();
            ownerUid = adminVO.getCompanyUid();
        }
        //获取自动生成人员编号
        SequenceVO sequenceVO = new SequenceVO();
        sequenceVO.setOwnerType(ownerType);
        sequenceVO.setOwnerUid(ownerUid);
        sequenceVO.setBusiType(EBusiType.userServiceOrderCode);
        sequenceVO.setCodeType(EBusinessType.userServiceAutoCode);
        Sequence sequence = sequenceService.customizeSelect(sequenceVO);
        String code = sequenceService.generateSerialCode(sequence);
        return code;
    }

    @Override
    public String getAutoOrderCode(String companyUid) {
        if (companyUid == null) {
            throw new RuntimeException("系统错误无法找到当前用户所属信息");
        }
        //获取自动生成人员编号
        SequenceVO sequenceVO = new SequenceVO();
        sequenceVO.setOwnerType(2);
        sequenceVO.setOwnerUid(companyUid);
        sequenceVO.setBusiType(EBusiType.userServiceOrderCode);
        sequenceVO.setCodeType(EBusinessType.userServiceAutoCode);
        Sequence sequence = sequenceService.customizeSelect(sequenceVO);
        String code = sequenceService.generateSerialCode(sequence);
        return code;
    }
    @Override
    public UserServiceOrderVO getUserOrderInfo(UserServiceOrderVO userServiceOrderVO) {
        return userServiceOrderMapper.getOrderByUserId(userServiceOrderVO.getEmployeeUid());
    }
}
